﻿// function injectCustomJS(jsPath) {
//   jsPath = jsPath || "js/inject.js";
//   var temp = document.createElement("script");
//   temp.setAttribute("type", "text/javascript");
//   temp.src = chrome.runtime.getURL(jsPath);
//   temp.onload = function () {
//     this.remove(); //执行完移除
//   };
//   document.body.appendChild(temp);
// }
// injectCustomJS();
function saveLocal(key, value) {
  chrome.storage.local.set({ [key]: value });
}
async function getLocal(key) {
  const result = await chrome.storage.local.get([key]);
  return result[key];
}

function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
/****************************/
const insertHTML = '<div class="grab_btn">点击开始拉取职位</div>';

const utils = {
  grabStatus: 0, //0：未开始，1：拉取中，2：拉取结束，3：拉取结束
  grabVal: 0, //当前抓取页面的结构类型
  sleep(time = 0) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, time);
    });
  },
  async initGrab() {
    this.jobList = [];
    const site = utils.getSite();
    this.site = site;
    this.grabCount = this.grabCount || 0;
    await this.sleep(1000);
    if (site == 'liepin') {
      if ($('#lp-search-job-box .job-list-box').length) {
        this.grabVal = 1;
        this.bindLPEvt();
      } else if ($('.left-list-box .job-list-item').length) {
        this.grabVal = 2;
        this.bindLPEvt();
      } else {
        //console.info("查找列表失败", this.grabCount);
        this.grabCount++;
        if (this.grabCount < 3) {
          await this.sleep(1000);
          this.initGrab();
        } else {
          this.grabCount = 0;
        }
      }
    } else if (site == 'zhipin') {
      if ($('.job-list-box .job-card-wrapper').length) {
        this.grabVal = 3;
        this.bindZPEvt();
      } else if ($('.position-job-list .job-card-box').length) {
        this.grabVal = 4;
        this.bindZPEvt();
      } else {
        this.grabCount++;
        //console.info("查找列表失败", this.grabCount);
        if (this.grabCount < 3) {
          await this.sleep(1000);
          this.initGrab();
        } else {
          this.grabCount = 0;
        }
      }
      // utils.bindZPEvt(site);
    }
  },
  resetGrab(site) {
    $('.grab_btn').html('拉取完成,刷新页面重置').addClass('grab_over');
    this.grabStatus = 3;
  },
  getSite() {
    const href = window.location.href;
    if (href.includes('liepin')) {
      return 'liepin';
    } else if (href.includes('zhipin')) {
      return 'zhipin';
    } else {
      return false;
    }
  },
  bindLPEvt() {
    var dom;
    if (this.grabVal == 1) {
      dom = $('.search-bar-qrcode');
      dom.html('');
      dom.prepend(insertHTML);
    } else if (this.grabVal == 2) {
      dom = $('.options-filter-content');
      dom.append(insertHTML);
    }
    dom.on('click', '.grab_btn', () => {
      const grabBtn = $('.grab_btn');
      if (this.grabStatus == 0) {
        this.startPull();
      } else if (this.grabStatus == 1) {
        this.grabEnd();
      } else if (this.grabStatus == 2) {
        this.postToServer();
      } else if (this.grabStatus == 3) {
        window.location.reload();
      }
    });
  },
  bindZPEvt() {
    var dom;
    if (this.grabVal == 3) {
      dom = $('.job-search-form');
      dom.after(insertHTML);
      dom = $('.job-search-box');
    } else if (this.grabVal == 4) {
      dom = $('.search-condition-inner');
      dom.append(insertHTML);
    }
    dom.on('click', '.grab_btn', () => {
      const grabBtn = $('.grab_btn');
      if (this.grabStatus == 0) {
        this.startPull();
      } else if (this.grabStatus == 1) {
        this.grabEnd();
      } else if (this.grabStatus == 2) {
        this.postToServer();
      } else if (this.grabStatus == 3) {
        window.location.reload();
      }
    });
  },
  startPull() {
    $('.grab_btn').html('正在拉取职位···').addClass('grab_ing');
    this.grabStatus = 1;
    if (this.site == 'liepin') {
      this.getLPJob();
    } else if (this.site == 'zhipin') {
      this.getZPJob();
    }
  },
  postToServer() {
    // 发送数据到后台
    const data = {
      type: 'preview',
      site: this.site,
      jobList: this.jobList
    };
	console.log('发送数据到background：',data)
    chrome.runtime.sendMessage(data, (response) => {
      if (response.code == 200) {
		console.log('接收到background响应');  
        this.resetGrab();
      }
    });
  },
  //初始化当前用户信息
  async postUserInfo(data) {
    const user = await getLocal('userVal');
    if (!user) return false;
    try {
      const userInfo = JSON.parse(user);
      if (userInfo && userInfo.user_id) {
        //console.log('查找成功：', userInfo);
        utils.initGrab();
      }
    } catch (e) {
      console.log('未查找到用户信息，查询失败');
    }
    // console.log("发送初始化信息：", { ...data, type: "init" });
    // chrome.runtime.sendMessage({ ...data, type: "init" }, (response) => {
    //   if (response.code == 200) {
    //     console.log("查找成功：", response);
    //     utils.initGrab();
    //   } else {
    //     //utils.initGrab();
    //     console.log("未查找到用户信息，查询失败");
    //   }
    // });
  },
  getLPJob(site) {
    if (this.grabStatus != 1) return false;
    const jobList = [];
    if (this.grabVal == 1) {
      $('.job-card-pc-container').each((index, item) => {
        const that = $(item);
        const tags = [];
        let companyScale = '';
        that.find('.company-tags-box span').each((i, t) => {
          const text = t.innerHTML;
          if (text?.endsWith('人') || text?.endsWith('人以上')) {
            companyScale = text;
          } else if (!text.endsWith('轮') && !/融资|其他|上市|以上/g.test(text)) {
            tags.push(text);
          }
        });
        const hr = that.find('.recruiter-name').html().split('·');
        const job = {
          name: that.find('.job-title-box > div:first-of-type').text(),
          avatar: that.find('.recruiter-photo img').attr('src'),
          location: that.find('.job-dq-box :nth-child(2)').html(),
          salary: that.find('.job-salary').html(),
          companyName: that.find('.company-name').html(),
          companyTags: tags,
          companyScale: companyScale,
          hr: hr[0],
          hrjob: hr[1],
          link: that.find('.job-detail-box a').attr('href')
        };
        jobList.push(job);
      });
    } else if (this.grabVal == 2) {
      const tlist = $('.company-header .name-right > p').html().replace(/ |\n/g, '').split('<span>·</span>');
      const tags = [];
      let companyScale = '';
      tlist.forEach((text, index) => {
        if (text?.endsWith('人') || text?.endsWith('人以上')) {
          companyScale = text;
        } else if (!text.endsWith('轮') && !/融资|其他|上市|以上/g.test(text)) {
          tags.push(text);
        }
      });
      const companyName = $('.company-header .title-box span.title').text();
      $('.job-card-pc-container').each((index, item) => {
        const that = $(item);
        const hrlist = that.find('.recruiter-name').text().split('·');
        const job = {
          name: that.find('.job-title-box > div:first-of-type').text(),
          avatar: that.find('.recruiter-photo img').attr('src'),
          location: that.find('.job-dq-box :nth-child(2)').text(),
          salary: that.find('.job-salary').text(),
          companyName,
          companyTags: tags,
          companyScale: companyScale,
          hr: hrlist[0]?.trim(),
          hrjob: hrlist[1]?.trim(),
          link: that.find('.job-detail-box a').attr('href')
        };
        jobList.push(job);
      });
    }
    this.jobList = this.jobList.concat(jobList);

    /* 继续拉取数据 */
    const scrollHeight = document.body.scrollHeight;
    $('html').animate(
      {
        scrollTop: scrollHeight - 1000
      },
      1500,
      () => {
        this.navToNextLPPage();
      }
    );
  },
  getZPJob() {
    if (this.grabStatus != 1) return false;
    const jobList = [];
    if (this.grabVal == 3) {
      $('.job-card-wrapper').each((index, item) => {
        const that = $(item);
        const tags = [];
        let companyScale = '';
        that.find('.company-tag-list li').each((i, t) => {
          const text = t.innerHTML;
          if (text?.endsWith('人') || text?.endsWith('人以上')) {
            companyScale = text;
          } else if (!text.endsWith('轮') && !/融资|其他|上市|以上/g.test(text)) {
            tags.push(text);
          }
        });
        const hr = that.find('.info-public').eq(0).contents();
        const job = {
          name: that.find('.job-name').text(),
          location: that.find('.job-area').text(),
          salary: that.find('.salary').html(),
          companyName: that.find('.company-name a').text(),
          companyTags: tags,
          companyScale: companyScale,
          hr: hr[0].nodeValue.trim(),
          hrjob: hr[1].innerText.trim(),
          link: window.location.origin + that.find('.job-card-body>a').attr('href')
        };
        jobList.push(job);
      });
    } else if (this.grabVal == 4) {
      const tlist = $('.info-primary .info p')
        .html()
        .replace(/<em(.+)><\/em>/g, '')
        .split('\n');
      const tags = [];
      let companyScale = '';
      tlist.forEach((text, index) => {
        text = text.trim();
        if (!text) return false;
        if (text.includes('<')) {
          text = $(text).text();
        }
        if (text?.endsWith('人') || text?.endsWith('人以上')) {
          companyScale = text;
        } else if (!text.endsWith('轮') && !/融资|其他|上市|以上/g.test(text) && text != '') {
          tags.push(text);
        }
      });
      const companyName = $('.info-primary .name h1')
        .text()
        .replace(/(.+)招聘$/, '$1');
      $('.job-card-box').each((index, item) => {
        const that = $(item);
        const hrlist = that.find('.boss-name').text().split('·');
        const job = {
          name: that.find('.job-name').text(),
          location: that.find('.company-location').text().replace(/ /g, ''),
          salary: that.find('.job-salary').text(),
          companyName,
          companyTags: tags,
          companyScale: companyScale,
          hr: hrlist[0]?.trim(),
          hrjob: hrlist[1]?.trim(),
          link: window.location.origin + that.find('.job-title a').attr('href')
        };
        jobList.push(job);
      });
    }
    this.jobList = this.jobList.concat(jobList);
    //console.info("jobList:", jobList);
    const scrollHeight = document.body.scrollHeight;
    $('html').animate(
      {
        scrollTop: scrollHeight - random(200,1500)
      },
      random(2000,4000),
      () => {
        this.navToNextZPPage();
      }
    );
  },
  grabEnd() {
    this.grabStatus = 2;
    $('.grab_btn').html(`拉取${this.jobList.length}条职位，点击下一步`).removeClass('grab_ing').addClass('grab_end');
    $('html').stop();
  },
  navToNextLPPage() {
    const next = $('.list-pagination-box .ant-pagination-item-active +.ant-pagination-item a');
    if (next.length == 0) {
      this.grabEnd();
    } else {
      next.get(0).click();
      setTimeout(() => {
        this.getLPJob();
      }, random(1000,3000));
    }
  },
  navToNextZPPage() {
    try {
      const next = $('.options-pages a.selected +a');
      if (next.length == 0 || !next.text()) {
        this.grabEnd();
      } else {
        next.get(0).click();
        setTimeout(() => {
          this.getZPJob();
        }, random(1200,2200));
      }
    } catch (e) {}
  },
  getUrlParam(name, urlStr = window.location.search.substr(1)) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = urlStr.match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  }
};

/*
 * 初始化
 */
const siteList = ['zhipin', 'liepin'];
$(() => {
  //console.log('初始化 content script');
  const site = utils.getSite();
  if (siteList.includes(site)) {
    utils.postUserInfo({
      site
    });
  }
});
